<?php
class EPMenuArrayParser extends EPMenuParser{

	function parse($data,&$root){
		if(!is_array($data)){
			throw new CException(Yii::t('epmenu','"data" is not an array.'));
		}
		$this->parseRecursive($data,$root);
		return $root;
	}

	private function parseRecursive($data,&$parent){


		if(isset($data['menuId'])){
			$parent->menuId=$data['menuId'];
			unset($data['menuId']);
		}

		if(isset($data['cssPrefix'])){
			$parent->cssPrefix=$data['cssPrefix'];
			unset($data['cssPrefix']);
		}

		if(isset($data['menuHtmlOptions'])){
			$parent->menuHtmlOptions=$data['menuHtmlOptions'];
			unset($data['menuHtmlOptions']);
		}

		if(isset($data['visible'])){
			$parent->visible=$data['visible'];
			unset($data['visible']);
		}

		if(isset($data[0])){
			//given as plain array
			$data=array('main'=>$data);
		}

		foreach($data as $pos=>$params){
			$position=EPMenuList::POS_MAIN;
			switch($pos){
				case 'begin':
					$position=EPMenuList::POS_BEGIN;
					break;
				case 'leading':
					$position=EPMenuList::POS_LEADING;
					break;
				case 'main':
					$position=EPMenuList::POS_MAIN;
					break;
				case 'addition':
					$position=EPMenuList::POS_ADDITION;
					break;
				case 'end':
					$position=EPMenuList::POS_END;
					break;
			}
			foreach($params as $entry){
				$menuItem=$parent->createMenuItem($position);
				$this->parseEntry($entry,$menuItem);
			}
		}




	}

	private function parseEntry($itemData,&$menuItem){
		$menuItem->label=$itemData[0];
		if(isset($itemData[1])){
			$menuItem->url=$itemData[1];
			unset($itemData[1]);
		}else{
			$menuItem->url=NULL;
		}

		unset($itemData[0]);
			
		if(isset($itemData['itemId'])){
			$menuItem->itemId=$itemData['itemId'];
			unset($itemData['itemId']);
		}

		if(isset($itemData['cssPrefix'])){
			$menuItem->cssPrefix=$itemData['cssPrefix'];
			unset($itemData['cssPrefix']);
		}
			
		if(isset($itemData['listItemHtmlOptions'])){
			$menuItem->listItemHtmlOptions=$itemData['listItemHtmlOptions'];
			unset($itemData['listItemHtmlOptions']);
		}
		
		if(isset($itemData['linkHtmlOptions'])){
			$menuItem->cssPrefix=$itemData['linkHtmlOptions'];
			unset($itemData['linkHtmlOptions']);
		}
		if(isset($itemData['submenu'])){
			$submenu=$menuItem->getSubMenu();
			$this->parseRecursive($itemData['submenu'],$submenu);
			if(isset($itemData['subMenuId'])){
				$submenu->menuId=$itemData['subMenuId'];
				unset($itemData['subMenuId']);
			}
			unset($itemData['submenu']);
		}

		if(isset($itemData['visible'])){
			$menuItem->visible=$itemData['visible'];
			unset($itemData['visible']);
		}


		if(!empty($itemData)){
			foreach($itemData as $k=>$v){
				$menuItem->setAttribute($k,$v);
			}
		}
	}

}